package com.ytf.dogbox.view;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.media.ThumbnailUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;

import androidx.annotation.DrawableRes;

import com.ytf.dogbox.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;



/**
 * @author tiwolf_li
 * @Date on 2020/6/24
 * @Description 这个主要是适用于led屏幕的，主要是因为led屏幕分辨率太低的缘故
 */
public class LedFirewormsView extends View implements Animator.AnimatorListener {

    private static final String TAG = "FirewormsFlyView";
    public static final int MAX_NUM = 25;

    private int mMeasuredWidth;
    private int mMeasuredHeight;

    private Random mRandom = new Random();

    private List<Particle> mCircles = new ArrayList<>();

    private Paint mPaint;
    private Bitmap mStarBitmap;
    private Bitmap musicBitmap;
    private Matrix mMatrix;
    private int mCurResId;
    private ValueAnimator mParticleAnim;
    private int musicWidth,musicHeight;
    private float musicAngle;

    private boolean isInit=false;//是否是初始化控件拿到的数据

    private int top=100;
    private int boxsize=100;
    private int snowSize=8;

    public LedFirewormsView(Context context) {
        super(context);
        isInit=true;
        init(context, null);
    }

    public LedFirewormsView(Context context, AttributeSet attrs) {
        super(context, attrs);
        isInit=true;
        init(context, attrs);
    }

    public LedFirewormsView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        isInit=true;
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        Log.e(TAG, "MusicFragment init: 雪花控件初始化" );
        if (mParticleAnim!=null)return;
        Log.e(TAG, "MusicFragment init: 雪花控件初始化0000" );
        try {
            if (mPaint==null)
                mPaint = new Paint();

            TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.LedFirewormsView);
            int resourceId = typedArray.getResourceId(R.styleable.LedFirewormsView_partical, R.mipmap.fire_star);
            int musicResourceId = typedArray.getResourceId(R.styleable.FirewormsView_particalSrc, R.mipmap.solarplay);
            if (isInit){
                top = typedArray.getInt(R.styleable.LedFirewormsView_topy, 100);
                boxsize = typedArray.getInt(R.styleable.LedFirewormsView_sizeBox,100);
                if (boxsize==300){
                    snowSize=30;
                }else if (boxsize==200){
                    snowSize=20;
                }else if (boxsize==250){
                    snowSize=25;
                }


            }

//            Log.e(TAG, "MusicFragment init: 雪花控件初始化,高度="+top+";控件大小="+boxsize );

//        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.FirewormsView);


            mCurResId = resourceId;

            // 打开抗锯齿
            mPaint.setAntiAlias(true);
            mPaint.setColor(Color.WHITE);
            mPaint.setAlpha(Particle.ALPHA_MAX);
            mPaint.setDither(true);
            mPaint.setStyle(Paint.Style.FILL);
            mMatrix = new Matrix();
            mStarBitmap = getParticleBitmap(resourceId);
            musicBitmap=getCenterBitmap(musicResourceId);
            musicWidth=musicBitmap.getWidth();
            musicHeight=musicBitmap.getHeight();
            setLayerType(View.LAYER_TYPE_HARDWARE, null);
            typedArray.recycle();

//            mParticleAnim = ValueAnimator.ofInt(0).setDuration(100);
//            mParticleAnim.setRepeatCount(ValueAnimator.INFINITE);
//            mParticleAnim.addListener(this);
        }catch (Exception e){
            e.printStackTrace();
            Log.e(TAG, "雪花: "+e.getLocalizedMessage());
        }

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (mMeasuredWidth == 0) {
            mMeasuredWidth = getMeasuredWidth();
            mMeasuredHeight = getMeasuredHeight();
        }
        Log.e(TAG, "onMeasure: 测试雪花数量,宽="+mMeasuredWidth+";高="+mMeasuredHeight );

        if (mCircles.size() == 0) {
            Log.e(TAG, "onMeasure: 雪花数量" );
            for (int i = 0; i < MAX_NUM; i++) {
                Particle f = new Particle(mStarBitmap, mMatrix, mPaint, getF() * mMeasuredWidth, getF() * mMeasuredHeight, mMeasuredWidth, mMeasuredHeight);
                mCircles.add(f);
            }
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.save();
        for (Particle circle : mCircles) {
            circle.drawItem(canvas);
        }
//                Log.e(TAG, "onDraw: 画了个音乐控件,宽："+musicWidth+";高："+musicHeight+";屏宽："+mMeasuredWidth+";屏高："+mMeasuredHeight+";顶高："+top );
        mMatrix.reset();
        mMatrix.setTranslate(mMeasuredWidth/2-musicWidth/2,top);
//        mMatrix.preTranslate(mMeasuredWidth/2,mMeasuredHeight/2);
        mMatrix.preRotate(musicAngle+=1f,musicWidth/2,musicHeight/2);
        canvas.drawBitmap(musicBitmap,mMatrix,mPaint);

        canvas.restore();
    }

    public void setParticleSrcID(@DrawableRes int resId) {
        if (mCurResId == resId) {
            return;
        }
        mCurResId = resId;
        for (Particle circle : mCircles) {
            circle.setDrawBitmap(getParticleBitmap(resId));
        }
        invalidate();
    }

    public void setParticleSrcBitmap(Bitmap bitmap) {
        for (Particle circle : mCircles) {
            circle.setDrawBitmap(bitmap);
        }
        invalidate();
    }

    private Bitmap getCenterBitmap(@DrawableRes int resId) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        return ThumbnailUtils.extractThumbnail(BitmapFactory.decodeResource(getContext().getResources(), resId, options), dip2px(boxsize), dip2px(boxsize), ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
    }

    private Bitmap getParticleBitmap(@DrawableRes int resId) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        return ThumbnailUtils.extractThumbnail(BitmapFactory.decodeResource(getContext().getResources(), resId, options), dip2px(snowSize), dip2px(snowSize), ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
//        return Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getContext().getResources(), resId, options),
//                dip2px(30), dip2px(30), true);
    }

    private float getF() {
        float v = mRandom.nextFloat();
        if (v < 0.15f) {
            return v + 0.15f;
        } else if (v >= 0.85f) {
            return v - 0.15f;
        } else {
            return v;
        }
    }

    public void startFly() {
        isInit=false;

        if (mParticleAnim==null){
//            Log.e(TAG, "onMeasure: 雪花动画初始化" );
            mParticleAnim = ValueAnimator.ofInt(0).setDuration(100);
            mParticleAnim.setRepeatCount(ValueAnimator.INFINITE);
            mParticleAnim.addListener(this);
            mParticleAnim.start();
        } else {
            if (!mParticleAnim.isRunning()) {
//            Log.d(TAG, "onMeasure  anim start  : ");
//                Log.e(TAG, "onMeasure: 雪花动画重新开始"+mParticleAnim.isRunning() );
                mParticleAnim.end();
                mParticleAnim.start();
            }
        }
    }

    public void stopFly() {
        if (mParticleAnim!=null && mParticleAnim.isRunning()){
            Log.e(TAG, "stopFly: 停止雪花飞1111" );
            mParticleAnim.end();
            mParticleAnim.cancel();
        }

    }

    public void cancelValueAnim(){
        if (mParticleAnim!=null && mParticleAnim.isRunning()){
//            Log.e(TAG, "cancelValueAnim: MusicFragment-销毁控件，停止动画" );
            mParticleAnim.end();
            mParticleAnim.cancel();
            mParticleAnim.removeAllUpdateListeners();
        }
    }

    private int dip2px(float value) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, getContext().getResources().getDisplayMetrics());
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
//        Log.d(TAG, "onDetachedFromWindow: ");
        if (null != mParticleAnim) {
            mParticleAnim.end();
            mParticleAnim = null;
        }
    }


    @Override
    public void onAnimationStart(Animator animation) {
        Log.e(TAG, "onAnimationStart: 雪花开始动画");
    }

    @Override
    public void onAnimationEnd(Animator animation) {
        Log.e(TAG, "onAnimationStart: 雪花结束动画");
    }

    @Override
    public void onAnimationCancel(Animator animation) {
        Log.e(TAG, "onAnimationStart: 雪花取消动画");
    }

    @Override
    public void onAnimationRepeat(Animator animation) {
        invalidate();
    }
}
